package io.esirong.eye.lifecycle;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

/**
 * Activity生命周期的回调。
 * Created by 黄嵘才(HuangRc) on 2019/10/8.
 */
public class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {

    private static final String TAG = ActivityLifecycle.class.getSimpleName();
    private final ActivitiesManager mManager;
    /** 当前活动的Activity页面 */
    private Activity currentActivity;
    /** 应用APP在前台显示 */
    private boolean foreground = false;

    ActivityLifecycle(ActivitiesManager activitiesManager) {
        this.mManager = activitiesManager;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Log.d(TAG, "onActivityCreated:" + activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {
        Log.d(TAG, "onActivityStarted:" + activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.d(TAG, "onActivityResumed:" + activity);
        this.currentActivity = activity;
        mManager.setEnter(activity);
        //从后台到前台显示时，先显示本应用展示面
        if (justAppOnBackground()) {
            foreground = true;
            notifyForeground();

        }
    }

    @Override
    public void onActivityPaused(Activity activity) {
        Log.d(TAG, "onActivityPaused:" + activity);
        mManager.setLeave(activity);
    }

    @Override
    public void onActivityStopped(Activity activity) {
        Log.d(TAG, "onActivityStopped:" + activity);

        //结合之前的Activity实例与当前生命周期的Activity，如相同则进入后台
        if (currentActivity != null && currentActivity == activity) {
            foreground = false;
            notifyBackground();
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        Log.d(TAG, "onActivitySaveInstanceState:" + activity);
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.d(TAG, "onActivityDestroyed:" + activity);
        if (currentActivity != null && currentActivity == activity) {
            currentActivity = null;
            foreground = false;
        }
    }

    /**
     * 检查应用是不是置于后台
     */
    private boolean justAppOnBackground() {
        return !foreground;
    }

    private void notifyForeground() {
        // This is where you can notify listeners, handle session tracking, etc
        Log.d(TAG, "App went foreground");
    }

    private void notifyBackground() {
        // This is where you can notify listeners, handle session tracking, etc
        Log.d(TAG, "App went background");
    }
}
